<template>
	<el-dialog
	  :title="dataForm.userId ? '修改员工信息' : '新增员工信息'"
	  :visible.sync="visible"
	  :before-close="close"
	  :close-on-click-modal="false"
	  width="30%">
	  <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-position="top">
	  	<el-form-item prop="username" label="员工工号(账号)">
        <el-input v-model="dataForm.username" placeholder="员工工号(账号)" :disabled="dataForm.userId ? true :  false"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="员工姓名">
        <el-input v-model="dataForm.name" placeholder="员工姓名" :disabled="dataForm.userId ? true :  false"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="账号密码" v-if="!dataForm.userId">
        <el-input v-model="dataForm.password" placeholder="账号密码" show-password></el-input>
      </el-form-item>
      <el-form-item prop="passwordAgain" label="确认密码" v-if="!dataForm.userId">
        <el-input v-model="passwordAgain" placeholder="确认密码" show-password></el-input>
      </el-form-item>
      <el-form-item prop="roles" label="员工角色">
        <el-select v-model="dataForm.roles" value-key="roleId" v-if="roles.length" multiple filterable placeholder="员工角色" style="width: 100%">
          <el-option
            v-for="item in roles"
            :key="item.roleId"
            :label="item.roleName"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="types" label="数据权限(只对业务流程模块生效)">
        <el-select v-model="dataForm.types" value-key="checkTypeId" v-if="types.length" multiple filterable placeholder="数据权限" style="width: 100%">
          <el-option
            v-for="item in types"
            :key="item.checkTypeId"
            :label="item.checkTypeName"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="departmentId" label="所属部门">
        <el-select v-model="dataForm.departmentId" filterable v-if="departments.length" placeholder="所属部门" style="width: 100%">
          <el-option
            v-for="item in departments"
            :key="item.departmentId"
            :label="item.departmentName"
            :value="item.departmentId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="workshopId" label="所属车间" v-if="workshopVisible">
        <el-select v-model="dataForm.workshopId" v-if="workshops.length" filterable placeholder="所属车间" style="width: 100%">
          <el-option
            v-for="item in workshops"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="positionId" label="员工职位" v-if="positionVisible">
        <el-select v-model="dataForm.positionId" v-if="positions.length" filterable placeholder="员工职位" style="width: 100%">
          <el-option
            v-for="item in positions"
            :key="item.positionId"
            :label="item.positionName"
            :value="item.positionId">
          </el-option>
        </el-select>
      </el-form-item>
			<el-form-item prop="inspectionGroupNames" label="所属小组" v-if="groupVisible">
			  <el-select v-model="dataForm.inspectionGroupNames" multiple v-if="groups.length" @change="setGroupIds" filterable placeholder="所属小组" style="width: 100%">
			    <el-option
			      v-for="item in groups"
			      :key="item.inspectionGroupId"
			      :label="item.inspectionGroupName"
			      :value="item.inspectionGroupName">
			    </el-option>
			  </el-select>
			</el-form-item>
	  </el-form>
	  <span slot="footer" class="dialog-footer">
	    <el-button @click="close">取 消</el-button>
	    <el-button type="primary" class="pan-btn primary-btn" @click="dataFormSubmit('dataForm')">确 定</el-button>
  	</span>
	</el-dialog>
</template>

<script>
	import { getDepartmentList } from '@/api/department'
	import { getWorkshopList } from '@/api/workshop'
	import { getPositionList } from '@/api/position'
	import { getRoleList } from '@/api/role'
  import { getCheckTypes } from '@/api/check'
	import { saveOrUpdateUser } from '@/api/user'
	import { getGroupList } from '@/api/inspection'
	import {CODE_OK} from '@/common/js/config'
	export default {
		data() {
			return {
				passwordAgain: "",
				visible: false,
				departments: [],
				workshops: [],
				positions: [],
				allPositions: [],
				roles: [],
        types: [],
				groups: [],
				dataForm: {
					username: "",
					name: "",
					password: "",
					departmentId: "",
					departmentName: "",
					workshopId: "",
					workshopName: "",
					positionId: "",
					positionName: "",
          roles: [],
					// roleIds: [],
					// roleNames: [],
					inspectionGroupIds: "",
					inspectionGroupNames: "",
          types: []
				},
				dataRule: {
					username: [
          	{ required: true, message: '员工工号不能为空', trigger: 'blur' }
        	],
        	name: [
          	{ required: true, message: '员工姓名不能为空', trigger: 'blur' }
        	],
        	password: [
          	{ required: true, message: '账号密码不能为空', trigger: 'blur' }
        	],
        	departmentId: [
          	{ required: true, message: '所属部门不能为空', trigger: 'blur' }
        	],
        	roles: [
          	{ required: true, message: '员工角色不能为空', trigger: 'blur' }
        	],
          types: [
          	{ required: true, message: '数据权限不能为空', trigger: 'blur' }
          ]
				}
			}
		},
		props: ["childDataForm"],
		created() {
			if (!this.childDataForm == null || !this.childDataForm == "" || this.childDataForm || !this.childDataForm == undefined) {
				this.dataForm = this.childDataForm
        if (this.dataForm.inspectionGroupNames != null) {
          let inspectionGroupNames = JSON.parse(JSON.stringify(this.dataForm.inspectionGroupNames))
          this.dataForm.inspectionGroupNames = inspectionGroupNames.split(",")
        }
			}
			this.visible = true
			this.getUserCorrelationInfo()
		},
		computed: {
			//如果是生产部，那么选择车间
			workshopVisible() {
				for (let i=0,j=this.departments.length; i<j; i++) {
					if (this.departments[i].departmentName == '生产部') {
						if (this.departments[i].departmentId == this.dataForm.departmentId) {
							return true
						}
					}
				}
				return false
			},
			//如果选择的部门有职位，那么选择职位
			positionVisible() {
				for (let i=0,j=this.allPositions.length; i<j; i++) {
					if (this.dataForm.departmentId == this.allPositions[i].departmentId) {
						this.positions = this.allPositions.filter(item => {
							return item.departmentId == this.dataForm.departmentId
						})
						return true
					}
				}
				return false
			},
			//如果职位为检验QC，选小组
			groupVisible() {
				for (let i=0,j=this.allPositions.length; i<j; i++) {
					if (this.allPositions[i].positionName == '检验QC' || this.allPositions[i].positionName == '内勤QC' || this.allPositions[i].positionName == '中控QC') {
						if (this.dataForm.positionId == this.allPositions[i].positionId) {
							return true
						}
					}
				}
				return false
			}
		},
		methods: {
      setGroupIds() {
        let ids = []
        for (let n of this.dataForm.inspectionGroupNames) {
          for (let g of this.groups) {
            if (n == g.inspectionGroupName) {
              ids.push(g.inspectionGroupId)
            }
          }
        }
        this.dataForm.inspectionGroupIds = ids.join(",")
      },
			close() {
				this.$emit('close')
				this.$emit('refreshData')
				this.visible = false
			},
			getUserCorrelationInfo() {
				const params = {
	        page: 1,
	        limit: 9999999
	      }
				getDepartmentList(params).then(res => {
					if (res.code === CODE_OK) {
						this.departments = res.page.list
					}else{
						this.$message.error(res.msg)
					}
				}).catch()
				getPositionList(params).then(res => {
					if (res.code === CODE_OK) {
						this.allPositions = res.page.list
					}else{
						this.$message.error(res.msg)
					}
				}).catch()
				getRoleList(params).then(res => {
					if (res.code === CODE_OK) {
						this.roles = res.page.list.filter(r => {
              return r.roleName != '超管'
            })
					}else{
						this.$message.error(res.msg)
					}
				}).catch()
        getCheckTypes().then(res => {
        	if (res.code === CODE_OK) {
        		this.types = res.list
            if (!this.dataForm.userId) {
              this.dataForm.types = res.list
            }
        	}else{
            this.$message.error(res.msg)
          }
        }).catch()
				getWorkshopList(params).then(res => {
					if (res.code === CODE_OK) {
						this.workshops = res.page.list
					}else{
						this.$message.error(res.msg)
					}
				}).catch()
				getGroupList(params).then(res => {
					if (res.code === CODE_OK) {
						this.groups = res.page.list
					}else{
						this.$message.error(res.msg)
					}
				}).catch()
			},
			dataFormSubmit(form) {
				if (this.workshopVisible && this.dataForm.workshopId == '') {
					this.$message.error("请选择所属车间")
					return
				}
				if (this.positionVisible && this.dataForm.positionId == '') {
					this.$message.error("请选择员工职位")
					return
				}
				if (this.groupVisible && this.dataForm.inspectionGroupIds == '') {
					this.$message.error("请选择所属小组")
					return
				}
				if (this.passwordAgain != this.dataForm.password && !this.dataForm.userId) {
					this.$message.error("两次密码不一致")
					return
				}
        if (this.dataForm.inspectionGroupNames != null) {
          if (this.dataForm.inspectionGroupNames.length != 0) {
            this.dataForm.inspectionGroupNames = this.dataForm.inspectionGroupNames.join(",")
          }
        }
				this.$refs[form].validate(valid => {
					if (valid) {
						//过滤修改信息
						if (this.dataForm.status == '正常') {
							this.dataForm.status = 0
						}else if(this.dataForm.status == '冻结'){
							this.dataForm.status = 1
						}
						if (!this.workshopVisible) {
							this.dataForm.workshopId = null
						}
						if (!this.positionVisible) {
							this.dataForm.positionId = null
						}
						saveOrUpdateUser(this.dataForm).then(res => {
							if (res.code === CODE_OK) {
								this.$message({
	                message: '操作成功',
	                type: 'success',
	                duration: 1500,
	                onClose: this.close()
              	})
							}else{
								this.$message.error(res.msg)
							}
						}).catch()
					}else{
						this.$message.error("请按要求填写")
					}
				})
			}
    }
	}
</script>

<style>
</style>
